import logging

from django.db import models
from django.utils import timezone

from common.tools.qinius import QNApi
from common.utils import get_class
from qixiaobao import settings
import redis

logger = logging.getLogger('qixiaobao')


def transforms_int(string_a, default=None):
    """把string转换为int"""
    if string_a is None:
        return default

    try:
        return int(str(string_a).strip())
    except ValueError:
        return default


class RedisID(object):
    """redis生成id"""

    def __init__(self, key,
                 host=settings.SESSION_REDIS_HOST,
                 port=settings.SESSION_REDIS_PORT,
                 db=settings.SESSION_REDIS_DB,
                 password=settings.SESSION_REDIS_PASSWORD):
        if not key:
            raise ValueError("RedisTasks must have a key string")
        self.num = 10000
        self.key = key
        self.r = redis.StrictRedis(host=host, port=port, db=db, password=password)
        # print('redis连接成功！')

    def refresh_num(self, amount=None):
        if not amount:
            amount = self.num
        key = self.key + '_max_id'
        max_id = transforms_int(self.r.get(key))
        max_new = max_id + amount
        self.r.delete(self.key)
        pipe = self.r.pipeline()
        for i in range(max_id + 1, max_new + 1):
            pipe.sadd(self.key, i)
        pipe.execute()
        self.r.set(key, max_new)
        return max_new

    def generate_id(self, amount=None):
        if not amount:
            amount = self.num
        key = self.key + '_max_id'
        max_id = transforms_int(self.r.get(key))
        length = self.r.scard(self.key)
        if length >= amount:
            return 'No need'
        if max_id:
            max_new = max_id + amount - length
            pipe = self.r.pipeline()
            for i in range(max_id + 1, max_new + 1):
                pipe.sadd(self.key, i)
            pipe.execute()
            self.r.set(key, max_new)
            return max_new
        return None

    def set_id(self, start, stop=None):
        if not stop:
            stop = start + self.num
        pipe = self.r.pipeline()
        for i in range(start, stop + 1):
            pipe.sadd(self.key, i)
        pipe.execute()
        self.r.set(self.key + '_max_id', stop)
        return self.r.scard(self.key)

    def get_id(self):
        v = self.r.spop(self.key)
        self.generate_id()
        if v:
            return str(v, encoding="utf-8")
        else:
            return v


class Common(models.Model):
    id = models.CharField('ID', primary_key=True, max_length=30, blank=True)
    misc_desc = models.TextField('描述', blank=True, default='')
    # 0.有效 1.无效 2.待审核 订单状态流程：2.处理中 0.完成 1.超过半小时无效
    STATUS_VALID = 0
    STATUS_INVALID = 1
    STATUS_REVIEW = 2

    STATUS_TYPE = (
        (STATUS_VALID, '有效'),
        (STATUS_INVALID, '无效'),
        (STATUS_REVIEW, '待审核'),
    )

    status = models.IntegerField('状态', default=STATUS_REVIEW, choices=STATUS_TYPE)
    create_time = models.DateTimeField('创建时间', default=timezone.now)
    last_mod_time = models.DateTimeField('最后修改时间', auto_now=True)

    class Meta:
        abstract = True

    def save(self, *args, **kwargs):
        if not self.id:
            r = RedisID(self._meta.app_label + '_' + self._meta.object_name)
            self.id = r.get_id()
            if not self.id:
                model_class = get_class(self._meta.app_label, self._meta.object_name)
                s_list = model_class.objects.all().order_by('-id')
                if s_list.exists():
                    u_id = transforms_int(s_list.first().id)
                    r.set_id(u_id + 1)
                else:
                    r.set_id(2000000)
                self.id = r.get_id()
        return super(Common, self).save(*args, **kwargs)


class CommonAuto(models.Model):
    id = models.AutoField(u'ID', primary_key=True)
    misc_desc = models.TextField(u'描述', blank=True, default='')
    # 0.有效 1.无效 2.待审核 订单状态流程：2.处理中 0.完成 1.超过半小时无效
    STATUS_VALID = 0
    STATUS_INVALID = 1
    STATUS_REVIEW = 2

    STATUS_TYPE = (
        (STATUS_VALID, '有效'),
        (STATUS_INVALID, '无效'),
        (STATUS_REVIEW, '待审核'),
    )

    status = models.IntegerField(u'状态', default=STATUS_REVIEW, choices=STATUS_TYPE)
    create_time = models.DateTimeField(u'创建时间', default=timezone.now)
    last_mod_time = models.DateTimeField(u'最后修改时间', auto_now=True)

    @staticmethod
    def get_null_string():
        return ''

    class Meta:
        abstract = True


class CommonSocial(models.Model):
    """社会化记录"""
    store_num = models.PositiveIntegerField(u'收藏数', default=0)
    share_num = models.PositiveIntegerField(u'分享数', default=0)
    comment_num = models.PositiveIntegerField(u'评论数', default=0)
    like_num = models.PositiveIntegerField(u'点赞数', default=0)
    play_num = models.PositiveIntegerField(u'播放数', default=0)
    pre_sale = models.PositiveIntegerField(u'预售数量', default=0)
    sale = models.PositiveIntegerField(u'销售量', default=0)
    unreal_num = models.PositiveIntegerField(u'添加销售量', default=0, blank=True)

    def show_sale(self):
        return self.unreal_num + self.sale

    class Meta:
        abstract = True


class MusicInfo(Common):
    """音频"""
    title = models.CharField(u'名称', max_length=20, default='')
    image = models.CharField(u'封面图片', max_length=100, default='', blank=True)
    path = models.CharField(u'音乐路径', max_length=100, default='')
    name = models.CharField(u'歌手', max_length=20, default='', blank=True)
    singer = models.CharField(u'歌手图片', max_length=100, default='', blank=True)
    size = models.PositiveIntegerField(u'文件大小(B)', default=0, blank=True)
    duration = models.PositiveIntegerField(u'时长(s)', default=0, blank=True)
    desc = models.TextField(u'内容', default='', blank=True)

    def get_path_url(self):
        return QNApi().getdwurl('qixiaobao', self.path)

    class Meta:
        db_table = 'music_info'
        verbose_name = '音频'
        ordering = ['-create_time']


class DetailComponent(CommonAuto):
    """
    活动详情组件
    type-content字段示例:
        RICH_TEXT: {'title': '活动描述', 'desc': '<p><strong>泰美国际新安中心店：南京路北段黄沙坪家属楼下</strong></p>'}
            MUSIC: 32423
              TEL: [18569408340, 18569408340]
          ADDRESS: [{title: '丰台小区店', addr: '北京市丰台区XX小区XX号', LAL: '116.141, 39.871'}]
            PRIZE: [{name: '橡皮一块', picture_url: 'https://www.show.com/XX/xxx.png', desc: '奖品描述'}]
           DFSHOP: [23433, 45342, 53253]
    """
    shop = models.ForeignKey('shop.ShopInfo', verbose_name=u'店铺', null=True, on_delete=models.SET_NULL,
                             related_name='component_shop')
    title = models.CharField(u'组件名称', max_length=100, default='', blank=True)
    RICH_TEXT, MUSIC, TEL, ADDRESS, PRIZE, DFSHOP = 0, 1, 2, 3, 4, 5
    COMPONENT_TYPES = (
        (RICH_TEXT, u'富文本'),
        (MUSIC, u'音乐'),
        (TEL, u'电话'),
        (ADDRESS, u'地址'),
        (PRIZE, u'奖品'),
        (DFSHOP, u'异业联盟'),
    )
    type = models.IntegerField(u'组件类型', choices=COMPONENT_TYPES, default=RICH_TEXT, blank=True)
    content = models.TextField(u'组件内容', default='', blank=True)

    def __unicode__(self):
        return self.title

    @classmethod
    def get_redis_key(cls, id):
        return '%s_%s_%s' % (cls._meta.app_label, cls.__name__, id)

    class Meta:
        db_table = 'detail_components'
        verbose_name = u'组件库'
        ordering = ['-create_time']
